package org.example;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws Exception {
        final long start = System.currentTimeMillis();
        int num = 1000000; //  依次增加到100万个数组成员
        AtomicInteger count = new AtomicInteger(0);
        CountDownLatch wg = new CountDownLatch(num);
        ThreadFactory threadFactory = Thread.ofVirtual().inheritInheritableThreadLocals(true).factory();
        for (int i = 0; i < num; i++) {
            final int params = i;
            threadFactory.newThread(() -> {
                if (mocRequest(params) == params) {
                    count.addAndGet(1);
                    wg.countDown();
                }
            }).start();
        }
        wg.await();
        // 减去2秒(2000ms)，是因为任务本身耗时2秒，最终剩余时间都是协程从启动到完成消耗的时间
        long useMs = System.currentTimeMillis() - start - 2000;
        System.out.printf("100万routine从启动到执行结束，所有协程本身总计耗时：%d ms, routine 执行的总次数：%d\n", useMs, count.get());
    }

    // 模拟一个类似http请求数据获取结果的函数
    static int mocRequest(int params) {
        // 模拟功能代码执行耗时为 2s
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return params;
    }


}